import requests
import json


def baidu_translate(word):
    url = 'https://fanyi.baidu.com/sug'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://fanyi.baidu.com/',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }

    data = {
        'kw': word
    }

    try:
        response = requests.post(url, headers=headers, data=data)
        response.encoding = 'utf-8'  # 设置编码
        result = response.json()

        if result.get('errno') == 0 and result.get('data'):
            print("\n翻译结果如下：")
            for item in result['data']:
                print(f"{item['k']} -> {item['v']}")
        else:
            print("未查询到相关翻译结果。")

    except requests.exceptions.RequestException as e:
        print(f"网络请求出错: {e}")
    except json.JSONDecodeError:
        print("无法解析服务器返回的数据，请稍后再试。")


if __name__ == '__main__':
    user_input = input("请输入要翻译的英文单词或中文词语：").strip()
    if user_input:
        baidu_translate(user_input)
    else:
        print("输入内容不能为空！")